package com.mudrov.anagram.core;

import com.mudrov.anagram.helpers.InputTextReader;
import com.mudrov.anagram.helpers.StringParser;
import com.mudrov.anagram.helpers.WordParser;

import java.util.HashSet;
import java.util.TreeSet;

public class AnagramStorage implements Anagram<HashSetCollection> {

	private TreeSet<HashSetCollection> allAnagrams;
	private InputTextReader textReader;

	public AnagramStorage(InputTextReader textReader){
		this.textReader = textReader;
	}

	@Override
	public TreeSet<HashSetCollection> getAnagramList() {
		if(allAnagrams != null)
			return allAnagrams;
		allAnagrams = new TreeSet<HashSetCollection>();
		getAllAnagrams();
		return allAnagrams;
	}

	private void getAllAnagrams(){
		WordParser strParser = new StringParser();
        HashSet<String> wordsSet = new HashSet<String>();
		while(textReader.hasNextPiece()){
			String stringToParse = textReader.getNextPieceOfText();
			String[] arrayWords = strParser.parseSomeString(stringToParse);
            for (String i : arrayWords)
                wordsSet.add(i);
		}
        for(String word : wordsSet){
            HashSetCollection someAnagram = new HashSetCollection(word);
            if(!allAnagrams.contains(someAnagram)){
                allAnagrams.add(someAnagram);
                continue;
            }
            for (HashSetCollection oneAnagrams : allAnagrams)
                if(oneAnagrams.equals(someAnagram))
                    oneAnagrams.addToAnagram(word);
        }
	}
}
